package cn.edu.ncut.cs.springboot.petmanagementsystem.service.Impl;

import cn.edu.ncut.cs.springboot.petmanagementsystem.dto.PetInformationDto;
import cn.edu.ncut.cs.springboot.petmanagementsystem.mapper.PetMapper;
import cn.edu.ncut.cs.springboot.petmanagementsystem.pojo.Pet;
import cn.edu.ncut.cs.springboot.petmanagementsystem.service.PetService;
import cn.edu.ncut.cs.springboot.petmanagementsystem.vo.PetInformationVo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.transaction.Transactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class PetServiceImpl implements PetService {

    @Autowired
    private PetMapper petMapper;

    /**
     * 分页动态查询宠物信息
     * @param pageNO
     * @param pageSize
     * @param petName
     * @param petType
     * @param gender
     * @return
     */
    @Override
    public IPage<PetInformationVo> getPetsByCondition(Integer pageNO, Integer pageSize,
                                                      String petName, String petType, Integer gender){
        IPage<PetInformationVo> petIPage = new Page<>(pageNO, pageSize);
        petIPage = petMapper.getPetsByCondition(petIPage,petName,petType,gender);
        return petIPage;
    }

    @Override
    public void UpdatePetInformation(PetInformationDto petInformationDto) {
        if (petInformationDto == null || petInformationDto.getId() == null) {
            throw new IllegalArgumentException("宠物ID不能为空");
        }
        
        Pet pet = petMapper.selectById(petInformationDto.getId());
        if (pet == null) {
            throw new RuntimeException("宠物不存在");
        }
        
        if(petInformationDto.getPetName() != null){
            pet.setPetName(petInformationDto.getPetName());
        }
        if(petInformationDto.getCategoryId() != null){
            pet.setCategoryId(petInformationDto.getCategoryId());
        }
        if(petInformationDto.getBreed() != null){
            pet.setBreed(petInformationDto.getBreed());
        }
        if (petInformationDto.getAge() != null){
            pet.setAge(petInformationDto.getAge());
        }
        if(petInformationDto.getGender() != null){
            pet.setGender(petInformationDto.getGender());
        }
        if(petInformationDto.getPrice() != null){
            pet.setPrice(petInformationDto.getPrice());
        }
        if(petInformationDto.getOriginalPrice() != null){
            pet.setOriginalPrice(petInformationDto.getOriginalPrice());
        }
        if(petInformationDto.getMainImage() != null){
            pet.setMainImage(petInformationDto.getMainImage());
        }
        if(petInformationDto.getImages() != null){
            pet.setImages(petInformationDto.getImages());
        }
        if(petInformationDto.getDescription() != null){
            pet.setDescription(petInformationDto.getDescription());
        }
        if(petInformationDto.getHealthStatus() != null){
            pet.setHealthStatus(petInformationDto.getHealthStatus());
        }
        if(petInformationDto.getVaccinationStatus() != null){
            pet.setVaccinationStatus(petInformationDto.getVaccinationStatus());
        }
        if(petInformationDto.getSterilizationStatus() != null){
            pet.setSterilizationStatus(petInformationDto.getSterilizationStatus());
        }
        if(petInformationDto.getPetStatus() != null){
            pet.setPetStatus(petInformationDto.getPetStatus());
        }
        if(petInformationDto.getOwnerId() != null){
            pet.setOwnerId(petInformationDto.getOwnerId());
        }
        if(petInformationDto.getEmployeeId() != null){
            pet.setEmployeeId(petInformationDto.getEmployeeId());
        }
        
        pet.setUpdateTime(LocalDateTime.now());
        int result = petMapper.updateById(pet);
        if (result <= 0) {
            throw new RuntimeException("更新宠物信息失败");
        }
    }



    @Transactional(rollbackOn = Exception.class)
    public boolean deletePetById(Long id) {
        try {
            // 1. 参数校验
            if (id == null || id <= 0) {
                log.warn("删除宠物失败：ID不能为空或无效，id={}", id);
                return false;
            }

            // 2. 使用MyBatis-Plus的逻辑删除功能
            // deleteById会自动将deleted字段设置为true（配置的logic-delete-value）
            int result = petMapper.deleteById(id);

            if (result > 0) {
                log.info("逻辑删除宠物成功，id={}", id);
                return true;
            } else {
                log.warn("逻辑删除宠物失败：宠物不存在或已被删除，id={}", id);
                return false;
            }

        } catch (Exception e) {
            log.error("删除宠物异常，id={}", id, e);
            throw new RuntimeException("删除宠物失败", e);
        }
    }

    @Override
    @Transactional(rollbackOn = Exception.class)
    public boolean deletePetBatch(List<Long> ids) {
        try {
            // 1. 参数校验
            if (ids == null || ids.isEmpty()) {
                log.warn("批量删除宠物失败：ID列表为空");
                return false;
            }

            // 2. 过滤有效ID
            List<Long> validIds = ids.stream()
                    .filter(id -> id != null && id > 0)
                    .distinct()
                    .collect(Collectors.toList());

            if (validIds.isEmpty()) {
                log.warn("批量删除宠物失败：无有效ID");
                return false;
            }

            // 3. 使用MyBatis-Plus的批量逻辑删除功能
            // deleteBatchIds会自动将deleted字段设置为true（配置的logic-delete-value）
            int result = petMapper.deleteBatchIds(validIds);

            if (result > 0) {
                log.info("批量逻辑删除宠物成功，数量={}，ids={}", result, validIds);
                return true;
            } else {
                log.warn("批量删除宠物失败：宠物不存在或已被删除，ids={}", validIds);
                return false;
            }

        } catch (Exception e) {
            log.error("批量删除宠物异常，ids={}", ids, e);
            throw new RuntimeException("批量删除宠物失败", e);
        }
    }

    @Override
    public boolean createPet(PetInformationDto petInformationDto) {
        // 1️⃣ 参数校验
        if (petInformationDto == null) {
            throw new IllegalArgumentException("宠物信息不能为空");
        }

        // 2️⃣ DTO -> 实体映射
        Pet pet = new Pet();
        pet.setId(null);
        pet.setPetName(petInformationDto.getPetName());
        pet.setCategoryId(petInformationDto.getCategoryId());
        pet.setBreed(petInformationDto.getBreed());
        pet.setAge(petInformationDto.getAge());
        pet.setGender(petInformationDto.getGender());
        pet.setPrice(petInformationDto.getPrice());
        pet.setOriginalPrice(petInformationDto.getOriginalPrice());
        pet.setMainImage(petInformationDto.getMainImage());
        pet.setImages(petInformationDto.getImages());
        pet.setDescription(petInformationDto.getDescription());
        pet.setHealthStatus(petInformationDto.getHealthStatus());
        pet.setVaccinationStatus(petInformationDto.getVaccinationStatus());
        pet.setSterilizationStatus(petInformationDto.getSterilizationStatus());
        pet.setPetStatus(petInformationDto.getPetStatus());
        pet.setOwnerId(petInformationDto.getOwnerId());
        pet.setEmployeeId(petInformationDto.getEmployeeId());
        pet.setViewCount(petInformationDto.getViewCount() == null ? 0 : petInformationDto.getViewCount());
        pet.setLikeCount(petInformationDto.getLikeCount() == null ? 0 : petInformationDto.getLikeCount());
        pet.setDeleted(false); // 默认未删除
        pet.setCreateTime(LocalDateTime.now());
        pet.setUpdateTime(LocalDateTime.now());

        // 3️⃣ 插入数据库
        int rows = petMapper.insert(pet);

        // 4️⃣ 返回执行结果
        return rows > 0;
    }

    @Override
    public List<PetInformationVo> getUserPets(Long userId) {
        if (userId == null) {
            log.warn("获取用户宠物列表失败：用户ID为空");
            return List.of();
        }
        
        try {
            List<PetInformationVo> pets = petMapper.getUserPets(userId);
            return pets != null ? pets : List.of();
        } catch (Exception e) {
            log.error("获取用户宠物列表异常，userId={}", userId, e);
            return List.of();
        }
    }

    @Override
    public PetInformationVo getPetById(Long id) {
        if (id == null) {
            log.warn("获取宠物详情失败：ID为空");
            return null;
        }
        
        try {
            PetInformationVo pet = petMapper.getPetById(id);
            if (pet == null) {
                log.warn("获取宠物详情失败：宠物不存在，id={}", id);
            }
            return pet;
        } catch (Exception e) {
            log.error("获取宠物详情异常，id={}", id, e);
            return null;
        }
    }
}
